package com.leo.common.security.server.exception;

import com.leo.common.core.enums.ExceptionCodeEnum;
import com.leo.common.core.model.Result;
import com.leo.common.core.util.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.annotation.Resource;

/**
 * @author johnny
 * @date 2018/7/8
 */
@RestControllerAdvice
@Slf4j
@Order(1)
public class GlobalOauthExceptionHandler {

	@Resource
	MessageUtils messageUtils;

	/***
	 * 404处理
	 * @param e NoHandlerFoundException
	 * @return Result
	 */
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.OK)
	public Result<Void> notFountHandler(NoHandlerFoundException e) {
		log.error("404 ex={}", e.getMessage(), e);
		String mst = messageUtils.get("NOT_FOUND") + ":" + e.getRequestURL();
		Result<Void> result = new Result<>();
		result.setCode(HttpStatus.NOT_FOUND.value());
		result.setMsg(mst);
		return result;
	}

	@ExceptionHandler(BadCredentialsException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.OK)
	public Result<Void> badClientCredentialsException(BadCredentialsException e) {
		log.error("400 ex={}", e.getMessage(), e);
		return Result.error(ExceptionCodeEnum.AUTH_BAD_CREDENTIALS_EXCEPTION);

	}

	@ExceptionHandler(AccessDeniedException.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.OK)
	public Result<Void> accessDeniedException(AccessDeniedException e) {
		log.error("400 ex={}", e.getMessage(), e);
		return Result.error(ExceptionCodeEnum.AUTH_ACCESS_DENIED);

	}

}
